import time
import datetime
import wsgiref.handlers

import appdb
import recorddt
import queryfmt
import apperr

import logging
log = logging.getLogger("query")

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.runtime import DeadlineExceededError

class QueryBase(webapp.RequestHandler):
  def get(self):
    start = time.time()
    try:
      output = "html" if not self.request.get("output") else self.request.get("output")
      data = self.getData()
      if "html" == output:
        fmt = self.getHTMLFormatter()
      elif "json" == output:
        fmt = self.getJSONFormatter()
      fmt.respond(self, data, start)
    except (Exception, db.Timeout, DeadlineExceededError), e:
      if "html" == output:
        fmt = self.getHTMLErrorFormatter()
        fmt.respond(self, e, start)

    self.responded()
  
  def responded(self):
    return
  
  def getHTMLErrorFormatter(self):
    return queryfmt.HTMLErrorFormatter()
        
class QueryRecord(QueryBase):
  def getData(self):
    if self.request.get("q").find("+") >= 0:
      tags = self.request.get("q").split("+")
    else:
      tags = self.request.get("q").split(" ")
    return (tags, appdb.QueryRecordsByTag(self.request.get("begin"),
                                          self.request.get("end"),
                                          tags))
  
  def getJSONFormatter(self):
    return queryfmt.RecordJSONFormatter()

  def getHTMLFormatter(self):
    return queryfmt.RecordHTMLFormatter()
  
class QueryNextTag(QueryBase):
  def getData(self):
    pagesize = 10
    if self.request.get("pagesize").isdigit():
      pagesize = int(self.request.get("pagesize"));
    tags, bookmark, prev = appdb.GetNextTags(self.request.get("q"),
                                             self.request.get("prevtag"), pagesize)
    
    return (tags, bookmark, prev)
  
  def getJSONFormatter(self):
    return queryfmt.NextTagJSONFormatter()    

  def getHTMLFormatter(self):
    return queryfmt.NextTagHTMLFormatter()

class QueryRelatedTag(QueryBase):
  def getData(self):
    pagesize = 10
    if self.request.get("pagesize").isdigit():
      pagesize = int(self.request.get("pagesize"));
    tags, bookmark = appdb.GetRelatedTags(self.request.get("q"), pagesize)
    
    return tags
  
  def getJSONFormatter(self):
    return queryfmt.RelatedTagJSONFormatter()    

  def getHTMLFormatter(self):
    return queryfmt.RelatedTagHTMLFormatter()

class QueryHistory(QueryBase):
  def getData(self):
    found = True
    if "false" == self.request.get("found"):
      found = False
    
    results = appdb.History.gql("WHERE found = :1 ORDER BY qcount ASC", found)
    return results.fetch(20)

  def getJSONFormatter(self):
    return queryfmt.HistoryJSONFormatter()    

  def getHTMLFormatter(self):
    return queryfmt.HistoryHTMLFormatter()

class QueryTagIndex(QueryBase):
  def getData(self):
    self.found = False
    data = appdb.QueryTagIndexByWords(self.request.get("q"))
    self.found = bool(len(data[0][0]) == len(self.request.get("q")))
    return data

  def getJSONFormatter(self):
    return queryfmt.TagIndexJSONFormatter()

  def getHTMLFormatter(self):
    return queryfmt.TagIndexHTMLFormatter()
  
  def responded(self):
    appdb.UpdateHistory(self.request.get("q"), self.found)

def main():
  application = webapp.WSGIApplication([("/queryrecord", QueryRecord),
                                        ("/querynexttag", QueryNextTag),
                                        ("/queryrelatedtag", QueryRelatedTag),
                                        ("/querytagindex", QueryTagIndex),
                                        ("/queryhistory", QueryHistory)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
